﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Threading;

namespace ContosoDashboard.Web
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ContosoService : IContosoService
    {
        private IClientNotificationService _client;
        private Timer _updateTimer;
        private CustomerInfo _update;
        private long _lastId = 0;

        private CustomerInfo[] _names =
            new[]
            {
                new CustomerInfo { Name = "Smith", Phone = "555-7770", City = "London", Email = "smith@mcnext.com" },
                new CustomerInfo { Name = "Dupont", Phone = "555-7771", City = "Paris", Email = "dupont@mcnext.com" },
                new CustomerInfo { Name = "Li", Phone = "555-7772", City = "Beijing", Email = "li@mcnext.com" },
                new CustomerInfo { Name = "Kennedy", Phone = "555-7773", City = "Washington", Email = "kennedy@mcnext.com" },
                new CustomerInfo { Name = "O'Connor", Phone = "555-7774", City = "Dublin", Email = "oconnor@mcnext.com" },
                new CustomerInfo { Name = "Hajjar", Phone = "555-7775", City = "Bagdad", Email = "hajjar@mcnext.com" },
            };

        public void Subscribe()
        {
            _client = OperationContext.Current.GetCallbackChannel<IClientNotificationService>();
            _updateTimer = new Timer(TimerTick, null, 1000, 5000);
        }

        private void TimerTick(object state)
        {
            if (_client != null)
            {
                try
                {
                    RefreshUpdate();
                    _client.SendUpdate(_update);
                }
                catch (Exception)
                {
                    _client = null;
                    _updateTimer.Dispose();
                }
            }
        }

        private void RefreshUpdate()
        {
            var r = new Random();
            var i = r.Next(0, _names.Length - 1);

            if (_update == null)
            {
                _update = new CustomerInfo
                {
                    Id = _lastId++,
                    Name = _names[i].Name,
                    Phone = _names[i].Phone,
                    City = _names[i].City,
                    Email = _names[i].Email
                };
            }
            else
            {
                _update.Id = _lastId++;
                _update.Name = _names[i].Name;
                _update.Phone = _names[i].Phone;
                _update.City = _names[i].City;
            }
        }
    }
}
